package com.example.administrator.daydayappmarket.list.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.example.administrator.daydayappmarket.Contacts;
import com.example.administrator.daydayappmarket.R;
import com.example.administrator.daydayappmarket.list.activity.ListSecondBodyActivity;
import com.example.administrator.daydayappmarket.list.adapter.ListSolftAdapter;
import com.example.administrator.daydayappmarket.list.model.ListSolftItem;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * A simple {@link Fragment} subclass.
 */
public class ListSolftFragment extends Fragment {


    PullToRefreshListView listview;
    ImageView iamgeView;
    RelativeLayout emptyLayout;

    private RequestQueue requestQueue;
    private List<ListSolftItem> dataSolft;
    private ListSolftAdapter adapter;
    private List<ListSolftItem> dataHead;
    private View headView;
    private   String path="http://img.ttigame.com";

    private int  index=1;
    private TextView fragmentListsolftHeadTextVeiw00;
    private TextView fragmentListsolftHeadTextVeiw01;
    private ImageView fragmentListsolftHeadImageview10;
    private TextView fragmentListsolftHeadTextVeiw10;
    private TextView fragmentListsolftHeadTextVeiw11;
    private ImageView fragmentListsolftHeadImageview20;
    private TextView fragmentListsolftHeadTextVeiw20;
    private TextView fragmentListsolftHeadTextVeiw21;
    private ImageView fragmentListsolftHeadImageview00;

    public ListSolftFragment() {
        // Required empty public constructor
    }



    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);



        headView = LayoutInflater.from(getContext()).inflate(R.layout.list_solft_headview, null);
        //head
        //图2
        fragmentListsolftHeadImageview00 = (ImageView) headView.findViewById(R.id.fragment_listsolft_head_Imageview00);
        //文字2
        fragmentListsolftHeadTextVeiw00 = (TextView) headView.findViewById(R.id.fragment_listsolft_head_textVeiw00);
        fragmentListsolftHeadTextVeiw01 = (TextView) headView.findViewById(R.id.fragment_listsolft_head_textVeiw01);
        //图1
        fragmentListsolftHeadImageview10 = (ImageView) headView.findViewById(R.id.fragment_listsolft_head_Imageview10);
        //文字1
        fragmentListsolftHeadTextVeiw10 = (TextView) headView.findViewById(R.id.fragment_listsolft_head_textVeiw10);
        fragmentListsolftHeadTextVeiw11 = (TextView) headView.findViewById(R.id.fragment_listsolft_head_textVeiw11);
        //图3
        fragmentListsolftHeadImageview20 = (ImageView) headView.findViewById(R.id.fragment_listsolft_head_Imageview20);
        //文字3
        fragmentListsolftHeadTextVeiw20 = (TextView) headView.findViewById(R.id.fragment_listsolft_head_textVeiw20);
        fragmentListsolftHeadTextVeiw21 = (TextView) headView.findViewById(R.id.fragment_listsolft_head_textVeiw21);



        dataSolft = new ArrayList<>();
        dataHead = new ArrayList<>();


        requestQueue = Volley.newRequestQueue(getContext());
        solftRequest();

    }

    private void solftRequest() {

        StringRequest stringRequest = new StringRequest(Request.Method.GET, Contacts.LIST_SOLFT+index, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                if (response!=null){
                    try {
                        JSONArray arr = new JSONArray(response);
                        for (int i = 3; i < arr.length(); i++) {
                            JSONObject jsonObject = arr.getJSONObject(i);
                            JSONObject data = jsonObject.getJSONObject("data");
                            ListSolftItem listSolftItem = new ListSolftItem();
                            listSolftItem.strJson(data);
                            dataSolft.add(listSolftItem);
                        }

                        if (index==1) {
                            for (int i = 0; i < 3; i++) {
                                JSONObject jsonObject = arr.getJSONObject(i);
                                JSONObject data = jsonObject.getJSONObject("data");
                                ListSolftItem listSolftItem = new ListSolftItem();
                                listSolftItem.strJson(data);
                                dataHead.add(listSolftItem);
                            }
                        }
                        adapter.notifyDataSetChanged();
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                if (dataHead.get(1).getIcon_url().startsWith("h")){
                                    Glide.with(getContext()).load(dataHead.get(1).getIcon_url()).into(fragmentListsolftHeadImageview00);
                                }else {
                                    Glide.with(getContext()).load(path+dataHead.get(1).getIcon_url()).into(fragmentListsolftHeadImageview00);
                                }
                                fragmentListsolftHeadTextVeiw00.setText(dataHead.get(1).getName());
                                int i = Integer.parseInt(dataHead.get(1).getDownload_count());
                                int i4 = i / 10000;
                                fragmentListsolftHeadTextVeiw01.setText(i4+"万人下载");

                                if (dataHead.get(0).getIcon_url().startsWith("h")){
                                    Glide.with(getContext()).load(dataHead.get(0).getIcon_url()).into(fragmentListsolftHeadImageview10);
                                }else {
                                    Glide.with(getContext()).load(path+dataHead.get(0).getIcon_url()).into(fragmentListsolftHeadImageview10);
                                }
                                fragmentListsolftHeadTextVeiw10.setText(dataHead.get(0).getName());
                                int i1 = Integer.parseInt(dataHead.get(0).getDownload_count());
                                int i2 = i1 / 10000;
                                fragmentListsolftHeadTextVeiw11.setText(i2+"万人下载");

                                if (dataHead.get(2).getIcon_url().startsWith("h")){
                                    Glide.with(getContext()).load(dataHead.get(2).getIcon_url()).into(fragmentListsolftHeadImageview20);
                                }else {
                                    Glide.with(getContext()).load(path+dataHead.get(2).getIcon_url()).into(fragmentListsolftHeadImageview20);
                                }
                                fragmentListsolftHeadTextVeiw20.setText(dataHead.get(2).getName());
                                int i3 = Integer.parseInt(dataHead.get(2).getDownload_count());
                                double v1 = ((double) (i3 / 1000)) / 10.0;
                                fragmentListsolftHeadTextVeiw21.setText(v1+"万人下载");

                                //头部监听
                                headlistnerSolft();

                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                    }
                }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        stringRequest.setTag("s");
        requestQueue.add(stringRequest);

        requestQueue.start();


    }

    public void headlistnerSolft(){

        if (dataHead != null) {
            fragmentListsolftHeadImageview00.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getContext(), ListSecondBodyActivity.class);
                    intent.putExtra("path",Contacts.LIST_SECOND+ dataHead.get(1).getId());
                    intent.putExtra("tag",2);
                    startActivity(intent);
                }
            });

            fragmentListsolftHeadImageview10.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getContext(), ListSecondBodyActivity.class);
                    intent.putExtra("path",Contacts.LIST_SECOND+ dataHead.get(0).getId());
                    intent.putExtra("tag",2);
                    startActivity(intent);
                }
            });

            fragmentListsolftHeadImageview20.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getContext(), ListSecondBodyActivity.class);
                    intent.putExtra("path",Contacts.LIST_SECOND+ dataHead.get(2).getId());
                    intent.putExtra("tag",2);
                    startActivity(intent);
                }
            });
        }

    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        View view = inflater.inflate(R.layout.fragment_list_solft, container, false);
        listview= (PullToRefreshListView) view.findViewById(R.id.fragment_listsolft_pullToRefreshListView);
        iamgeView= (ImageView) view.findViewById(R.id.fragment_listsolft_empty_image);
        emptyLayout= (RelativeLayout) view.findViewById(R.id.fragment_listsolft_RelativeLayout_empty);

        adapter = new ListSolftAdapter(getContext(), dataSolft);
        listview.setAdapter(adapter);


        Glide.with(getContext()).load(R.drawable.cat_loading_transparent).into(iamgeView);
        listview.setEmptyView(emptyLayout);

        listview.getRefreshableView().addHeaderView(headView);

        listview.setMode(PullToRefreshBase.Mode.BOTH);

        listview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(final PullToRefreshBase<ListView> refreshView) {
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {

                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (dataSolft!=null) {
                                    dataSolft.clear();
                                }
                                index=1;
                                solftRequest();
                                refreshView.onRefreshComplete();
                            }
                        });

                    }
                },2000);
            }

            @Override
            public void onPullUpToRefresh(final PullToRefreshBase<ListView> refreshView) {

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        index++;
                        solftRequest();
                        refreshView.onRefreshComplete();
                    }
                });
            }
        });


        listview.getRefreshableView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (dataSolft!=null&&position>1) {
                    Intent intent = new Intent(getContext(), ListSecondBodyActivity.class);
                    intent.putExtra("path",Contacts.LIST_SECOND+ dataSolft.get(position-2).getId());
                    intent.putExtra("tag",2);
                    startActivity(intent);
                }
            }
        });
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        requestQueue.cancelAll("s");
    }
}
